import React, { Component } from 'react'

var BoilingVerdict = (props) => {
    if (props.temperature >= 100) {
        return <p>the water is boiling!</p>
    }
    return <p>the water is not boiling.</p>
}
// 摄氏度
function toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;
}

// 华氏温度
function toFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
    const input = parseFloat(temperature);
    if (Number.isNaN(input)) {
        return '';
    }
    const output = convert(input);
    const rounded = Math.round(output * 1000) / 1000;
    return rounded.toString();
}
const scaleNames = {
    c: 'Celsius',
    f: 'Fahrenheit'
}
class TemperatureInput extends Component {
    constructor(props) {
        super(props)
        this.state = {}
    }
    handleInputChange = (e) => {
        // 非受控组件获取value方式
        // var val = this.refs.input.value;
        // 受控组件获取value方式
        var val = e.target.value;
        this.props.onTemperature(val)
    }
    render() {
        let { type, temperature } = this.props
        return (
            <div>
                <h6>Enter temperature in {scaleNames[type]}</h6>
                <input onChange={this.handleInputChange} placeholder="请输入温度" value={temperature}></input>
                {/* <input onChange={this.handleInputChange} ref="input" placeholder="请输入温度"></input> */}
            </div>
        )
    }
}

class Calculator extends Component {
    constructor(props) {
        super(props)
        this.state = {
            temperature: "",
            type: 'c'
        }
    }
    handleInputChangeC = (temperature) => {
        this.setState({
            temperature,
            type: 'c'
        })
    }
    handleInputChangeF = (temperature) => {
        this.setState({
            temperature,
            type: 'f'
        })
    }
    render() {
        let { type, temperature } = this.state
        // 摄氏度
        let temperatureC = type === 'c' ? temperature : tryConvert(temperature, toCelsius)
        // 华氏温度
        let temperatureF = type === 'f' ? temperature : tryConvert(temperature, toFahrenheit)
        return (
            <div>
                <TemperatureInput temperature={temperatureC} onTemperature={this.handleInputChangeC} type="c" />
                <br></br>
                <TemperatureInput temperature={temperatureF} onTemperature={this.handleInputChangeF} type="f" />
                <BoilingVerdict temperature={temperatureC} />
            </div>
        )
    }
}
export default Calculator